#!/bin/bash

# 数据库连接检查脚本
echo "🔍 检查数据库连接状态..."

# 数据库配置
DB_HOST="localhost"
DB_PORT="3306"
DB_NAME="park-management"
DB_USER="root"
DB_PASS="root123123"

# 检查MySQL服务状态
echo "📊 检查MySQL服务..."
if command -v mysql &> /dev/null; then
    echo "✅ MySQL客户端已安装"
else
    echo "❌ MySQL客户端未安装"
    echo "💡 安装命令: brew install mysql@8.0"
    exit 1
fi

# 检查MySQL服务是否运行
echo "🔍 检查MySQL服务状态..."
if pgrep -f "mysqld" > /dev/null; then
    echo "✅ MySQL服务正在运行"
else
    echo "⚠️  MySQL服务可能未启动"
    echo "💡 启动命令: brew services start mysql@8.0"
fi

# 测试数据库连接
echo "🔗 测试数据库连接..."
if mysql -h$DB_HOST -P$DB_PORT -u$DB_USER -p$DB_PASS -e "SELECT 1;" 2>/dev/null; then
    echo "✅ 数据库连接成功"
else
    echo "❌ 数据库连接失败"
    echo "💡 请检查:"
    echo "   1. MySQL服务是否启动"
    echo "   2. 用户名密码是否正确"
    echo "   3. 数据库是否存在"
    exit 1
fi

# 检查数据库是否存在
echo "📁 检查数据库 '$DB_NAME'..."
DB_EXISTS=$(mysql -h$DB_HOST -P$DB_PORT -u$DB_USER -p$DB_PASS -e "SELECT COUNT(*) FROM information_schema.SCHEMATA WHERE SCHEMA_NAME='$DB_NAME';" -s -N 2>/dev/null)

if [ "$DB_EXISTS" = "1" ]; then
    echo "✅ 数据库 '$DB_NAME' 已存在"
    
    # 检查表是否已创建
    TABLE_COUNT=$(mysql -h$DB_HOST -P$DB_PORT -u$DB_USER -p$DB_PASS -e "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA='$DB_NAME';" -s -N 2>/dev/null)
    echo "📊 数据库中已有 $TABLE_COUNT 张表"
    
    if [ "$TABLE_COUNT" -gt 0 ]; then
        echo "✅ 数据库已初始化"
    else
        echo "⚠️  数据库存在但无表，需要初始化"
    fi
else
    echo "❌ 数据库 '$DB_NAME' 不存在"
    echo "💡 创建数据库:"
    echo "   mysql -u$DB_USER -p$DB_PASS -e \"CREATE DATABASE $DB_NAME DEFAULT CHARACTER SET utf8mb4;\""
fi

# 检查Redis
echo "🔍 检查Redis服务..."
if command -v redis-cli &> /dev/null; then
    if redis-cli ping 2>/dev/null | grep -q "PONG"; then
        echo "✅ Redis服务运行正常"
    else
        echo "⚠️  Redis服务可能未启动"
        echo "💡 启动命令: brew services start redis"
    fi
else
    echo "⚠️  Redis客户端未安装"
    echo "💡 安装命令: brew install redis"
fi

echo ""
echo "🎯 下一步操作:"
echo "1. 如果数据库未初始化: ./start-with-db.sh"
echo "2. 如果数据库已初始化: mvn clean install -DskipTests && mvn spring-boot:run -pl park-admin"